package com.imstlife.vending.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.MotionEvent;

import com.dwin.navy.serialportapi.com_track;
import com.dwin.navy.serialportapi.com_zhongji;
import com.imstlife.vending.api.MarvAPI;
import com.imstlife.vending.push.Constants;
import com.imstlife.vending.push.LogUtil;
import com.imstlife.vending.push.NotificationReceiver;
import com.imstlife.vending.sgy.logger.LocalLog;
import com.imstlife.vending.utils.Cof;
import com.imstlife.vending.utils.DeviceUtil;
import com.imstlife.vending.utils.GsonUtil;
import com.imstlife.vending.utils.NetUtil;
import com.imstlife.vending.utils.SharePersistentUtil;
import com.imstlife.vending.utils.T;
import com.imstlife.vending.vo.CheckOutRespone;
import com.imstlife.vending.vo.DrinkInfo;
import com.imstlife.vending.vo.SyncOutTradeResponse;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by lihaifeng on 16/10/27.
 */
public class BaseActivity extends FragmentActivity implements NetUtil.NetEvent{

    private static String TAG = "BaseActivity";

    /**
     * 接收推送广播
     */
    private DrinkInfoActivity.MainAcNotificationReceiver receiver;

    /**
     * 设备登陆后返回支付页面地址
     */
    public String notifyUrl = null;

    /***
     * 设备登陆后返回    支付回调地址
     */
    public String syncUrl = null;

    /**
     * 以勒串口API
     */
    private com_track yileSerial;

    /**
     * 中吉串口API
     */
    private com_zhongji zhongjiSerial;

    /**
     * 机型   以勒marv_vending_01 中吉marv_vending_02
     */
    public String deviceModel;

    public static NetUtil.NetEvent event;

    /**
     * 设备号
     */
    private String deviceId;


    /**
     * 自动检测订单计时器
     */
    private Timer timer ;
    /**
     * 自动检测订单任务
     */
    private TimerTask timerTask;

    /**
     * 自动重试次数统计
     */
    public int reTryCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        notifyUrl = getIntent().getStringExtra("notifyUrl");
        syncUrl = getIntent().getStringExtra("syncUrl");
        deviceModel = getIntent().getStringExtra("deviceModel");
        event = this;
        Log.i(TAG,"");
    }
    /**
     * 动态注册广播
     */
    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.ACTION_SHOW_NOTIFICATION);
        filter.addAction("connect");
        filter.addAction("disconnect");
        receiver = new DrinkInfoActivity.MainAcNotificationReceiver();
        registerReceiver(receiver, filter);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
//        AppManager.getInstance().finishActivity();

    }

    @Override
    public void onNetChange(int state) {

    }

    @Override
    protected void onResume() {
        reTryCount=0;
        super.onResume();
        String str = SharePersistentUtil.getSharePersistentString(this,"spnum");
        int iserial = Cof.SERIAL_PORT_NUM;
        if (str!=null&&!str.equals("")){
            iserial = Integer.parseInt(str);
        }

        if(Cof.MODEL_01.equals(deviceModel)){
            yileSerial = new com_track(iserial);
            yileSerial.openSerialPort();

        }else if(Cof.MODEL_02.equals(deviceModel)||Cof.MODEL_03.equals(deviceModel)||Cof.MODEL_04.equals(deviceModel)){
            zhongjiSerial  = com_zhongji.getInstance(iserial);
            zhongjiSerial.openSerialPort();

        }
        startTimer();
        initReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(Cof.MODEL_01.equals(deviceModel)){
            if(yileSerial!=null){
                yileSerial.closeSerialPort();
            }


        }else if(Cof.MODEL_02.equals(deviceModel)||Cof.MODEL_03.equals(deviceModel)||Cof.MODEL_04.equals(deviceModel)){
            if(zhongjiSerial!=null){
                zhongjiSerial.closeSerialPort();
            }


        }
        stopTimer();
        unregisterReceiver(receiver);
    }
    public void  autoReturn(){
    }

    /**
     * 启动订单检测
     */
    private void startTimer(){
        Log.i(TAG,"startTimer");
        timer = new Timer();
        timer.schedule(timerTask = new TimerTask() {
            @Override
            public void run() {
                checkOutState();
            }
        },1000,1000*3);
    }

    public void stopTimer(){
        reTryCount=0;
        Log.i(TAG,"stopTimer");
        if(timerTask!=null){
            timerTask.cancel();
            timerTask=null;
        }
        if(timer!=null){
            timer.cancel();
            timer=null;
        }

    }

    /**
     * 每次交互后重新记时
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        Log.i(TAG,"onTouchEvent retryCount:"+reTryCount);
        reTryCount =0;
        return super.onTouchEvent(event);
    }

    /**
     * 向服务端请求未出货的记录 重试 30次  间隔 20秒
     */
    private void checkOutState(){
        Log.i(TAG,"checkOutState");
        reTryCount++;
        MarvAPI.getInstance().checkOutState(Cof.Interface.URL_CHECK_OUT, DeviceUtil.getDeviceId(MyApplication.getInstance()), new MarvAPI.APIListener() {
            @Override
            public void onSuccess(Object data) {
                try{
                    CheckOutRespone respone = (CheckOutRespone) data;
                    if("0".equals(respone.getStatus())){//找到记录 可以出货
                        if(respone.getData()!=null)
                        {
                            out(Integer.valueOf(respone.getData().getNum()),respone.getData().getOutTradeNo());
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(String msg) {

            }

            @Override
            public void onNetError(String msg) {

            }
        });
        if(reTryCount>30){
            stopTimer();
            autoReturn();
        }
    }

    public void setDeviceId(String deviceId){
        this.deviceId = deviceId;
    }


    /**
     * 推送接收
     */
    public class MainAcNotificationReceiver extends BroadcastReceiver {

        private final String LOGTAG = LogUtil
                .makeLogTag(NotificationReceiver.class);
        public MainAcNotificationReceiver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(LOGTAG, "MainAcNotificationReceiver.onReceive()...");
            String action = intent.getAction();
            Log.d(LOGTAG, "lhfaction=" + action);
            if (Constants.ACTION_SHOW_NOTIFICATION.equals(action)) {
                String notificationId = intent
                        .getStringExtra(Constants.NOTIFICATION_ID);
                String notificationApiKey = intent
                        .getStringExtra(Constants.NOTIFICATION_API_KEY);
                String notificationTitle = intent
                        .getStringExtra(Constants.NOTIFICATION_TITLE);
                String notificationMessage = intent
                        .getStringExtra(Constants.NOTIFICATION_MESSAGE);
                String notificationUri = intent
                        .getStringExtra(Constants.NOTIFICATION_URI);
                Log.i(TAG,"收到推送："+notificationMessage);
                if(notificationMessage!=null&&!"".equals(notificationMessage)){
                    optionPushMsg(notificationMessage);
                }
            } else if ("disconnect".equals(action)) {
                disconnect();
            }

        }
    }

    /**
     * 推送中断，子类可以重写
     */
    public void disconnect(){

    }

    /**
     * 正在出货请等待，子类可以重写
     */
    public void plsWait(){

    }

    /**
     * 解析推送内容并出货
     * @param data
     */
    private void optionPushMsg(String data) {
        plsWait();
        DrinkInfo d = GsonUtil.getInstace().decodeMsgToDrinkInfo(data);
        Log.i(TAG,d.toString());
        out(d.getId(), d.getOutTradeNo());
    }
    //收到推送或者心跳  200    判断是否出货   出货 300
    //收到推送或者心跳  200    判断是否出货   没出货  发送出货指令  出货成功 0
    //收到推送或者心跳  200    判断是否出货   没出货  发送出货指令  出货失败 -1

    //收到推送或者心跳   告诉服务器 200   是否出过货  出过 300  没出过 发送出货指令  成功0  失败 -1

    //200 发起支付
    //300 重复出货
    //0
    //-1
    /**
     * 出货   以勒 串口若返回“” 则出货成功
     *        中吉太坑，  55aa  和  aa55  都不能稳定收到出货后的返回内容
     */
    private void out(final int dao, final String outTradeNo) {
        LocalLog.e("out","dao="+dao+"   outTradeNo="+outTradeNo);
        //告诉第三方 客户端收到支付成功
        syncOutTrade(200,outTradeNo);
        Log.i(TAG,"out()"+dao+" outTradeNo:"+outTradeNo);
        if(MyApplication.outTradeHistory.get(outTradeNo)!=null){//已经出过货了
            Log.i(TAG,"已经出过货");
            syncOutTrade(300,outTradeNo);
            return;
        }else{
            MyApplication.outTradeHistory.put(outTradeNo,System.currentTimeMillis());
            Log.i(TAG,"未出过货");
        }
        new Thread() {
            @Override
            public void run() {
                String retstr = null;
                try {
                    int idao = dao;
                    if(Cof.MODEL_01.equals(deviceModel)){
                        retstr = yileSerial.chu_huo_track(idao);
                        Log.i(TAG,"出货方式："+deviceModel);
                    }else if(Cof.MODEL_02.equals(deviceModel)||Cof.MODEL_03.equals(deviceModel)||Cof.MODEL_04.equals(deviceModel)){
                        retstr = zhongjiSerial.chu_huo_track(dao,deviceModel);
                        Log.i(TAG,"出货方式："+deviceModel);
                    }

                } catch (Exception e) {
                    retstr = "Exception: " + e.getMessage();
                }
//                if (true){
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            T.showLong(MyApplication.getInstance(), "出货成功");
//                            reduceLocal(dao + "");
//                            syncOutTrade(0,outTradeNo);
//                            outResult(0);
//                        }
//                    });
//                    return;
//                }
                final String hui = retstr;
                Log.d("out_return:","出货结果"+hui);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (null==hui||hui.length() == 0) {
                            LocalLog.e("out","出货结果=出货成功");
                            T.showLong(MyApplication.getInstance(), "出货成功");
                            reduceLocal(dao + "");
                            syncOutTrade(0,outTradeNo);
                            outResult(0);
                        } else {
                            LocalLog.e("out","出货结果=出货失败="+hui);
                            T.showLong(MyApplication.getInstance(), hui);
                            outResult(1);
                            syncOutTrade(-1,outTradeNo);
//                            if(Cof.MODEL_01.equals(deviceModel)){
//                                T.showLong(MyApplication.getInstance(), "出货失败");
//                                outResult(1);
//                                syncOutTrade(-1,outTradeNo);
//                            }else  {//中机的机器收不到返回 默认是为成功
//                                T.showLong(MyApplication.getInstance(), "出货成功" +System.currentTimeMillis());
//                                outResult(0);
//                                reduceLocal(dao + "");
//                                syncOutTrade(-1,outTradeNo);
//                            }
                        }
                    }
                });
            }
        }.start();

    }

    /**
     * 子类可重写，做不同业务，  商品信息页面 finish()  商品列表页面不处理
     * 0 出货成功
     * 1.出货失败
     */
    public void outResult(int state){

    }

    /**
     * 当前货道减少1瓶
     *
     * @param num
     */
    private void reduceLocal(String num) {
        int count = SharePersistentUtil.getSharePersistentInt(MyApplication.getInstance(), Cof.APP_IMAGE_CACHE, num);
        SharePersistentUtil.saveSharePersistent(MyApplication.getInstance(), Cof.APP_IMAGE_CACHE, num, count - 1);

    }

    /**
     * 同步出货成功状态   0成功   1失败
     * @param state
     */
    private void syncOutTrade(int state,String outTradeNo) {

        LocalLog.e("sync","syncOutTrade:"+state+"    outTradeNo:"+outTradeNo);
        if(syncUrl==null)
            return;
        syncUrl = syncUrl.replace(" ","");
        String deviceId = SharePersistentUtil.getSharePersistentString(MyApplication.getInstance(),Cof.KEY_DEVICE_ID);
        MarvAPI.getInstance().syncOutTrade(syncUrl, deviceId, outTradeNo, state, new MarvAPI.APIListener() {
            @Override
            public void onSuccess(Object data) {
                SyncOutTradeResponse response = (SyncOutTradeResponse) data;
                Log.i(TAG,response.getMsg());
                if("0".equals(response.getStatus())){
                    LocalLog.e("sync","ok");
                }else{
                    LocalLog.e("sync","fail="+(response.getStatus()==null?"":response.getStatus())+" "+(response.getMsg()==null?"":response.getMsg()));
                }
            }

            @Override
            public void onFailure(String msg) {
                LocalLog.e("sync","onFailure="+msg);
            }

            @Override
            public void onNetError(String msg) {
                LocalLog.e("sync","onNetError="+msg);
            }
        });
    }
}